package middleware

import (
	"server/global"
	"server/model"
	"server/myutils"
	"strconv"

	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
)

//通过api调用量来判定流量,依旧是redis缓存 只存储当天的数据
func FlowSetter() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		//当前的时间永远是today
		s, err := model.Redis.HGet(model.Ctx, "flow", myutils.Today).Result()
		if err == redis.Nil {
			s = "0"
			goto Start
		} else if err != nil {
			myutils.ResultJSON(ctx, global.MIDDLE_FAIL, nil)
			ctx.Abort()
			return
		}
	Start:
		i, _ := strconv.Atoi(s)
		i++
		model.Redis.HSet(model.Ctx, "flow", myutils.Today, strconv.Itoa(i)) //lastparam is TTL time ,only set settime will show
		ctx.Next()
	}
}
